package demo.advice;

import org.apache.commons.lang.time.StopWatch;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class PerformanceLoggingAdvice implements Ordered {
    private static final Logger log = Logger
            .getLogger(PerformanceLoggingAdvice.class);

    // Have the timing occur before spring transactionality by implementing a
    // high order
    private int order = 100;

    public int getOrder() {
        return this.order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    @Around("execution(* demo.*ServiceImpl.*(..))")
    public Object doPerformanceProfiling(ProceedingJoinPoint pjp)
            throws Throwable {
        StopWatch timer = new StopWatch();
        timer.start();
        Object retVal = pjp.proceed();

        final String target = pjp.getTarget().getClass().getSimpleName();
        final String method = pjp.getSignature().getName();
        final String description = target + "." + method + " executed in ";
        log.info(description + timer.getTime());

        return retVal;
    }

}
